import { createRouter, createWebHistory } from 'vue-router';
import { useRoute, useRouter } from "vue-router";
import { userMenu } from "../store/usermenu";
import { LoginApi } from "../request/api";

const Route = useRoute();

// 路由组件表
const Login = () => import(/* webpackChunkname: "login" */ '../views/Login.vue');
const Layout = () => import(/* webpackChunkname: "layout" */ '../views/Layout.vue');
const home = () => import(/* webpackChunkname: "home" */ '../components/home.vue');
const goods = () => import(/* webpackChunkname: "home" */ '../components/goods.vue');
const rentNote = () => import(/* webpackChunkname: "home" */ '../components/rentNote.vue');
const rentRequest = () => import(/* webpackChunkname: "home" */ '../components/rentRequests.vue');
const personal = () => import(/* webpackChunkname: "home" */ '../components/personal.vue');

const routes = [
    // { path: '/', redirect: '/layout' },
    {
        path: "/",
        name: "layout",
        component: Layout,
        redirect: '/home'
        // children: [
        //     { path: "/home", name: "home", component: home, },
        //     { path: "/goods", name: "goods", component: goods, },
        //     { path: "/rentNote", name: "rentNote", component: rentNote, },
        //     { path: "/rentRequests", name: "rentRequests", component: rentRequest, },
        //     { path: "/personal", name: "personal", component: personal, },
        // ]
    },
    { path: "/login", name: "login", component: Login },
]

const router = createRouter({
    history: createWebHistory(),
    routes
})

router.beforeEach((to, from, next) => {
    const token = localStorage.getItem("token");
    if (to.path == "/login" && token) {
        next("/");
        return
    }

    if (to.path !== "/login" && !token) {
        userMenu().resetUserMenu();
        next("/login")
        return
    }
    // 访问的是首页且存在token
    if (to.path !== "/login" && token && userMenu().menu.length == 0) {
        // 避免浏览器刷新时丢失菜单数据
        if (userMenu().menu.length == 0) {
            userMenu().BeifenMenu();
        }
        let Array = userMenu().menu.map(item => {
            return {
                title: item.title,
                path: item.path,
                // component: () => modules(`../components${item.path}.vue`),
                component: () => import(/* @vite-ignore */ '../components' + item.path + '.vue'),
                meta: {
                    titles: item.title,
                    paths: item.path
                }
            }
        });
        // 添加路由表
        Array.forEach(item => {
            router.addRoute("layout", item)
        });
        next(to.path);
        return
    }
    next()
})

export default router